package com.j3l11234.myy_sign.model;

import java.security.MessageDigest;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.j3l11234.myy_sign.entity.UserEntity;
import com.j3l11234.myy_sign.util.MyException;

@Service
public class UserModel {
	@Autowired
	private SessionFactory sessionFactory;
	
	
	public UserEntity login(String username, String password) throws MyException{
		Session session = null;
		UserEntity user = null;
		try {
			session = sessionFactory.openSession();	
			String hql="FROM UserEntity AS user WHERE user.username=:username AND user.password=:password";//使用命名参数，推荐使用，易读。
			Query query=session.createQuery(hql);
			query.setString("username", username);
			query.setString("password", string2MD5(password));
			user = (UserEntity)query.uniqueResult();
			
			if(user == null){
				throw new MyException("用户名或密码错误");
			}else{
				user.setLastLogin(new Date());
				Transaction tran = session.beginTransaction();  
				session.update(user);
				tran.commit();
			}
		} catch (MyException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw new MyException("数据库访问错误");
		}finally{
			if(session != null){
				session.close();
			}	
		}
		return user;
	}
	
	@SuppressWarnings("unchecked")
	public List<UserEntity> getUser() throws MyException{
		Session session = null;
		List<UserEntity> userList = null;
		try {
			session = sessionFactory.openSession();	
			String hql="FROM UserEntity AS user ";
			Query query=session.createQuery(hql);
			userList = (List<UserEntity>)query.list();		
		} catch (Exception e) {
			e.printStackTrace();
			throw new MyException("数据库访问错误");
		}finally{
			if(session != null){
				session.close();
			}	
		}
		return userList;
	}
	
	public UserEntity getUserByID(int user_id) throws MyException{
		Session session = null;
		UserEntity user = null;
		try {
			session = sessionFactory.openSession();	
			String hql="FROM UserEntity AS user WHERE user.id=:user_id";
			Query query=session.createQuery(hql);
			query.setInteger("user_id", user_id);
			user = (UserEntity)query.uniqueResult();		
		} catch (Exception e) {
			e.printStackTrace();
			throw new MyException("数据库访问错误");
		}finally{
			if(session != null){
				session.close();
			}	
		}
		return user;
	}
	
	public UserEntity addUser(String username,String password, String alias,int privilege) throws MyException{
		Session session = null;
		UserEntity user = null;
		try {
			session = sessionFactory.openSession();	
			String hql="FROM UserEntity AS user WHERE user.username=:username";
			Query query=session.createQuery(hql);
			query.setString("username", username);
			user = (UserEntity)query.uniqueResult();
			//不存在则新建
			if(user != null){
				throw new MyException("用户名重复");	
			}
			if(password.length() == 0){
				throw new MyException("密码不能为空");
			}
			user = new UserEntity();
			user.setPassword(string2MD5(password));
			user.setUsername(username);		
			user.setPrivilege(privilege);
			user.setAlias(alias);
			
			Transaction tran = session.beginTransaction();  
			session.save(user);
			tran.commit();
		} catch (MyException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw new MyException("数据库访问错误");
		}finally{
			if(session != null){
				session.close();
			}	
		}
		return user;
	}
	
	public UserEntity editUser(int user_id, String username,String password,String alias,int privilege) throws MyException{
		Session session = null;
		UserEntity user = null;
		try {
			session = sessionFactory.openSession();	
			String hql="FROM UserEntity AS user WHERE user.id=:user_id";
			Query query=session.createQuery(hql);
			query.setInteger("user_id", user_id);
			user = (UserEntity)query.uniqueResult();
			if(user == null){
				throw new MyException("用户不存在");
			}
			
			if(password.length() != 0){
				user.setPassword(string2MD5(password));
			}
			if(user_id != 1){
				user.setUsername(username);		
				user.setPrivilege(privilege);
			}
			user.setAlias(alias);
			
			Transaction tran = session.beginTransaction();  
			session.saveOrUpdate(user);
			tran.commit();
		} catch (MyException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw new MyException("数据库访问错误");
		}finally{
			if(session != null){
				session.close();
			}	
		}
		return user;
	}
	
	public UserEntity deleteUser(int user_id) throws MyException{
		Session session = null;
		UserEntity user = null;
		
		if(user_id == 1){
			throw new MyException("不能删除管理员 = =");
		}
		
		try {
			user = new UserEntity();
			user.setId(user_id);
			session = sessionFactory.openSession();				
			Transaction tran = session.beginTransaction();
			try {
				session.delete(user);
			} catch (HibernateException e) {
				tran.rollback();
				throw new MyException("删除失败");
			}
			
			tran.commit();
		} catch (MyException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw new MyException("数据库访问错误");
		}finally{
			if(session != null){
				session.close();
			}	
		}
		return user;
	}
	
	
	private static String string2MD5(String inStr){
		MessageDigest md5 = null;
		try{
			md5 = MessageDigest.getInstance("MD5");
		}catch (Exception e){
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++){
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
}
